package yx.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import yx.dao.BaseDaoInt;
import yx.model.BsVehicle;
import yx.vo.DatagridVO;
import yx.vo.VehicleVO;

@Service("vehicleService")
public class VehicleServiceImpl implements VehicleServiceInt {
	/**
	 * Logger for this class
	 */
	private static final Logger logger = Logger.getLogger(VehicleServiceImpl.class);

	private BaseDaoInt<BsVehicle> vehicleDao;

	public BaseDaoInt<BsVehicle> getVehicleDao() {
		return vehicleDao;
	}

	@Autowired
	public void setVehicleDao(BaseDaoInt<BsVehicle> vehicleDao) {
		this.vehicleDao = vehicleDao;
	}

	

	@Override
	public VehicleVO save(VehicleVO vehicle) {
		BsVehicle t = new BsVehicle();
		BeanUtils.copyProperties(vehicle, t);
		vehicleDao.save(t);
		BeanUtils.copyProperties(t, vehicle);
		return vehicle;
	}

	@Override
	public DatagridVO datagrid(VehicleVO vehicle) {
		DatagridVO dg = new DatagridVO();
		String hql = "from BsVehicle t";
		Map<String, Object> params = new HashMap<String, Object>();
		hql = addWhere(vehicle, hql, params);
		String totalHql = "select count(*) " + hql;
		hql = addOrder(vehicle, hql);
		List<BsVehicle> l = vehicleDao.find(hql, params, vehicle.getPage(), vehicle.getRows());
		List<VehicleVO> nl = new ArrayList<VehicleVO>();
		changeModel(l, nl);
		dg.setTotal(vehicleDao.count(totalHql, params));
		dg.setRows(nl);
		return dg;
	}

	private void changeModel(List<BsVehicle> l, List<VehicleVO> nl) {
		if (l != null && l.size() > 0) {
			for (BsVehicle t : l) {
				VehicleVO u = new VehicleVO();
				BeanUtils.copyProperties(t, u);
				nl.add(u);
			}
		}
	}

	private String addOrder(VehicleVO vehicle, String hql) {
		if (vehicle.getSort() != null || vehicle.getOrder() != null) {
			hql += " order by " + vehicle.getSort() + " " + vehicle.getOrder();
		}
		return hql;
	}

	private String addWhere(VehicleVO vehicle, String hql, Map<String, Object> params) {
		if (vehicle.getStudentId() != null) {
			hql += " where t.studentId = :studentId";
			params.put("studentId", vehicle.getStudentId());
		}
		return hql;
	}

	@Override
	public void remove(String ids) {
		String[] nids = ids.split(",");
		String hql = "delete BsVehicle t where t.id in (";
		for (int i = 0; i < nids.length; i++) {
			if (i > 0) {
				hql += ",";
			}
			hql += "'" + nids[i] + "'";
		}
		hql += ")";
		vehicleDao.executeHql(hql);
	}

	@Override
	public VehicleVO edit(VehicleVO vehicle) {
		BsVehicle t = vehicleDao.get(BsVehicle.class, vehicle.getId());
		BeanUtils.copyProperties(vehicle, t);
		return vehicle;
	}

}
